import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 创建异步对象
export const todoAsync = createAsyncThunk('asyncTodo', () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, 1000)
  })
})
const todoSlice = createSlice({
  name: 'todo',
  initialState: {
    todos: [
      {
        id: 1,
        todoName: '吃饭',
        isDone: false,
      },
      {
        id: 2,
        todoName: '做核酸',
        isDone: true,
      },
    ],
    loading: false,
    editId: undefined,
  },
  reducers: {
    updateTodo(state, action) {
      state.todos.forEach((item) => {
        if (item.id === action.payload) item.isDone = !item.isDone
      })
    },
    editTodo(state, action) {
      state.editId = action.payload
    },

    editTodoName(state, action) {
      state.todos.forEach((item) => {
        if (item.id === action.payload.id)
          item.todoName = action.payload.todoName
      })
    },
  },
  extraReducers(builder) {
    builder.addCase(todoAsync.fulfilled, (state, action) => {
      //   console.log(action)
      const todo = {
        id: Date.now(),
        todoName: action.meta.arg,
        isDone: false,
      }
      state.todos.push(todo)
      state.loading = false
    })
    builder.addCase(todoAsync.pending, (state, action) => {
      //   console.log(action)
      state.loading = true
    })
    builder.addCase(todoAsync.rejected, (state, action) => {
      //   console.log(action)
      state.loading = false
    })
  },
})

export default todoSlice
const { updateTodo, editTodo, editTodoName } = todoSlice.actions
export { updateTodo, editTodo, editTodoName }
